package builder

import (
	"crypto/rand"
	"fmt"
	"math/big"
	"time"
)

// StandardOrderBuilder 标准订单建造者
type StandardOrderBuilder struct {
	order *Order
}

func NewStandardOrderBuilder() *StandardOrderBuilder {
	return &StandardOrderBuilder{order: &Order{
		CreatedAt: time.Now(),
		Items:     []Item{},
	}}
}

// SetID 设置订单ID
func (b *StandardOrderBuilder) SetID() OrderBuilder {
	randInt, _ := rand.Int(rand.Reader, big.NewInt(1000000000))
	b.order.ID = fmt.Sprintf("ORD%09d", randInt.Int64())
	return b
}

// SetCustomer 设置订单客户
func (b *StandardOrderBuilder) SetCustomer(name, email, address string) OrderBuilder {
	b.order.Customer = Customer{
		Name:    name,
		Email:   email,
		Address: address,
	}
	return b
}

// SetItems 设置订单商品
func (b *StandardOrderBuilder) SetItems(items []Item) OrderBuilder {
	b.order.Items = items
	return b
}

// SetPayment 设置订单支付
func (b *StandardOrderBuilder) SetPayment(method string, amount float64) OrderBuilder {
	b.order.Payment = Payment{
		Method: method,
		Amount: amount,
	}
	return b
}

// SetShipping 设置订单配送
func (b *StandardOrderBuilder) SetShipping(method string, cost float64) OrderBuilder {
	b.order.Shipping = Shipping{
		Method: method,
		Cost:   cost,
	}
	return b
}

// Build 构建订单
func (b *StandardOrderBuilder) Build() *Order {
	// 自动计算支付金额
	if b.order.Payment.Amount == 0 {
		b.order.Payment.Amount = b.order.TotalAmount()
	}
	return b.order
}
